<script setup lang="ts">
import { formatDateTime } from '/@lib/utils/tool.ts'
import { sys_normal_disable } from '/@/const/Options.ts'
import { ModalUtil } from '/@lib/utils/modal.ts'
import { useModalStatus } from '/@lib/hooks/useModalStatus.ts'
import { useForm } from '/@lib/hooks/useForm.ts'
import { usePagination } from '/@lib/hooks/usePagination.ts'
import { useLoading } from '/@lib/hooks/useLoading.ts'
import { UserVO } from '/@/api/system/sysUser/types'
import { RoleVO } from '/@/api/system/sysRole/types'
import { ApiSysRole } from '/@/api/system/sysRole'


const { loading, showLoading, hideLoading } = useLoading()
const { modalVisible, modalTitle, showModal, hideModal, setModalTitle } = useModalStatus()
const closeCancel = () => {
  resetQueryForm()
  hideModal()
}
/** 打开 Modal 操作 */
const open = async (row: any) => {
  showModal()
  setModalTitle(`添加授权用户【角色名：${row.roleName}，权限标识：${row.roleKey}】`)
  await handleOpenDefaultData(row)
}
defineExpose({ open })
const emit = defineEmits(['submit-success'])
/** Modal Open 处理默认数据 */
const handleOpenDefaultData = async (row: RoleVO) => {
  queryParams.roleId = row.roleId as any
  await getTableList()
}
/** 提交按钮 */
const submitForm = async () => {
  try {
    showLoading()

    const userIds = ids.value.join(',')
    console.log('userIds', userIds)
    if (!userIds) {
      ModalUtil.notifyWarning('请选择要授权的用户')
      return
    }
    await ApiSysRole.authUser({ roleId: queryParams.roleId, userIds })
    ModalUtil.msgSuccess('操作成功')
    emit('submit-success')
    hideModal()
  } finally {
    hideLoading()
  }
}

/** 表格区域 */
const { pageNum, pageSize, total, setTotal, onChangeCurrent, onChangePageSize } = usePagination(() => getTableList())
const queryFormRef = ref()
const { form: queryParams, resetForm: resetQueryForm } = useForm({
  pageNum: computed(() => pageNum.value),
  pageSize: computed(() => pageSize.value),
  roleId: undefined,
  userName: undefined,
  phoneNumber: undefined
})
const tableRef = ref()
const tableData = ref([])

const ids = ref<Array<string | number>>([])
const idsLabel = ref<Array<string | number>>([])
const single = ref(true)
const multiple = ref(true)
const isShowAlert = computed(() => ids.value.length > 0)
const alertTitle = computed(() => `已选择：${ids.value.length} 项 ${idsLabel.value}`)

/** 搜索按钮操作 */
const handleQuery = () => {
  pageNum.value = 1
  getTableList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
/** 表格多选框选中数据 */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection.map((item) => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
  idsLabel.value = selection.map((item) => item.userName)
}

const getTableList = async () => {
  showLoading()
  try {
    const res = await ApiSysRole.authUserUnAllocatedList(queryParams)
    tableData.value = res.rows
    setTotal(res.total)
  } finally {
    hideLoading()
  }
}
// getTableList()
</script>

<template>
  <el-dialog
    class="authUserSelect-dialog"
    :title="modalTitle"
    v-model="modalVisible"
    width="80%"
    top="5vh"
    @close="closeCancel"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
  >
    <div class="flex-column flex-auto">
      <VipQueryForm>
        <VipQueryFormLeftPanel :span="24">
          <el-form ref="queryFormRef" :model="queryParams" inline label-width="80px" label-position="right">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="queryParams.phoneNumber"
                placeholder="请输入手机号码"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <!--   搜索按钮   -->
            <el-form-item>
              <el-button plain type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </VipQueryFormLeftPanel>
        <VipQueryFormBottomPanel v-if="isShowAlert">
          <el-alert type="info" :closable="false" :title="alertTitle"></el-alert>
        </VipQueryFormBottomPanel>
        <!--            <VipQueryFormRightPanel>-->
        <!--              <el-button icon="Plus" type="primary" @click="handleAdd">添加</el-button>-->
        <!--            </VipQueryFormRightPanel>-->
      </VipQueryForm>

      <div class="flex-auto">
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          style="height: 100%"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" width="55" align="center" />

          <!--  主内容   -->
          <el-table-column key="userName" label="登录账号" align="center" prop="userName" show-overflow-tooltip />
          <el-table-column key="nickName" label="用户昵称" align="center" prop="nickName" show-overflow-tooltip />
          <el-table-column key="deptName" label="部门" align="center" prop="deptName" show-overflow-tooltip />
          <el-table-column key="deptName" label="当前角色" align="center" prop="roleName" show-overflow-tooltip />
          <el-table-column key="phoneNumber" label="手机号码" align="center" prop="phoneNumber" width="120" />
          <el-table-column label="状态" align="center" prop="status" width="120">
            <template #default="scope">
              <VipDictTag :options="sys_normal_disable" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>

          <template #empty>
            <el-empty class="vip-data-empty" description="暂无数据" />
          </template>
        </el-table>
      </div>

      <VipPagination
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        @current-change="onChangeCurrent"
        @size-change="onChangePageSize"
      />
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div>
        <el-button @click="closeCancel">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.authUserSelect-dialog {
  height: 88vh !important;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .el-dialog__body {
    width: 100%;
    //height: 80%;
    flex: 1;
    display: flex;
    flex-flow: column;
    overflow: hidden;
  }
}
</style>

<style scoped lang="scss"></style>
